export function draggable(node: HTMLElement) {
	function dragStart(e: DragEvent) {
		let self: any = node;//this;
		e.dataTransfer!.setData("text/plain", (e.target as any)["id"]);
		self.classList.add("dragging");
		setTimeout(() => {
			self.classList.add("drag-hide-source");
		}, 0);
	}
	function dragEnd() {
		let self: any = node;//this;
		self.classList.remove("dragging");
		self.classList.remove("drag-hide-source");
	}
	node.addEventListener('dragstart', dragStart);
	node.addEventListener('dragend', dragEnd);
	return {
		destroy() {
			node.removeEventListener('dragstart', dragStart);
			node.removeEventListener('dragend', dragEnd);
		}
	};
}

export function droppable(node: HTMLElement) {
	function dragOver(e: DragEvent) {
		e.preventDefault();
	}
	function dragEnter(e: DragEvent) {
		e.preventDefault();
		let self = node;//this;
		self.classList.add("dragover");
	}
	function dragLeave(e: DragEvent) {
		let self = node;//this;
		self.classList.remove("dragover");
	}
	function dragDrop(e: DragEvent) {
		let self = node;//this;
		e.preventDefault();
		e.stopPropagation();
		self.classList.remove("dragover");
		let id = e.dataTransfer!.getData("text/plain");
		if (id) {
			let dragEl = document.getElementById(id);
			if (dragEl) (e.target as HTMLElement).append(dragEl);
		}
	}

	node.addEventListener('dragenter', dragEnter);
	node.addEventListener('dragleave', dragLeave);
	node.addEventListener('dragover', dragOver);
	node.addEventListener('drop', dragDrop);

	return {
		destroy() {
			node.removeEventListener('dragenter', dragEnter);
			node.removeEventListener('dragleave', dragLeave);
			node.removeEventListener('dragover', dragOver);
			node.removeEventListener('drop', dragDrop);
		}
	};
}